package com.example.customview;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class CustomLinearLayout extends LinearLayout {

	ImageView icon;
	TextView title,content;
	
	int measureWidth(int measureSpec){
		return View.resolveSize(480, measureSpec);
	}
	int measureHeight(int measureSpec) {
		int result = 800;//默认大小
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        switch (specMode) {
		case MeasureSpec.EXACTLY:
			result = specSize;
			break;
		case MeasureSpec.AT_MOST:
			result = Math.min(result, specSize);
			break;
		case MeasureSpec.UNSPECIFIED:
			//do nothing
			break;
		default:
			break;
		}
        return result;
	}
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		
		System.out.println("onMeasure");

		/*
		 * 先设置内部控件
		 */
		//用MeasureSpec.make()方法生成icon的widthSpec与heightSpec
		int widthSpec = MeasureSpec.makeMeasureSpec(240, MeasureSpec.getMode(widthMeasureSpec));
		int heightSpec = MeasureSpec.makeMeasureSpec(50, MeasureSpec.getMode(heightMeasureSpec));
		icon.measure(widthSpec, heightSpec);//icon.measure会调用icon.onMeasure(xx)方法
		title.measure(widthSpec, heightSpec);//title与icon用一样的measureSpec
		
		/*
		 * 设置外部控件
		 */
		widthMeasureSpec = measureWidth(widthMeasureSpec);
		heightMeasureSpec = measureHeight(heightMeasureSpec);
		this.setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
		
	}
	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		super.onLayout(changed, l, t, r, b);
		System.out.println("onLayout");
		icon.layout(50 , 20, 240, 50);
		title.layout(130 , 50, 300, 100);
	}
	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		super.onSizeChanged(w, h, oldw, oldh);
		System.out.println("onSizeChanged");
	}
	public CustomLinearLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		
		this.setOrientation(VERTICAL);

		icon = new ImageView(context);
		icon.setImageResource(R.drawable.ic_launcher);
		icon.setBackgroundColor(Color.parseColor("#f871e2"));
//		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(50, 50);
//		this.addView(icon,params);
		this.addView(icon);
		
		title = new TextView(context);
		title.setBackgroundColor(Color.parseColor("#9e6a8d"));
		title.setText("title");
		this.addView(title);
		
		content = new TextView(context);
		content.setText("content");
		content.setBackgroundColor(Color.parseColor("#29f13d"));
//		params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//		this.addView(content,params);
		this.addView(content);
		
	}
}
